package com.oauth.linkedin.server;

import java.util.List;

import org.gwtwidgets.server.spring.GWTSpringController;
import org.springframework.beans.factory.annotation.Autowired;

import com.oauth.common.server.util.OAuthRequestUtil;
import com.oauth.components.client.rpc.exception.SessionExpiredException;
import com.oauth.linkedin.client.beans.LinkedinModel;
import com.oauth.linkedin.client.beans.LinkedinUser;
import com.oauth.linkedin.client.exception.LinkedinOAuthException;
import com.oauth.linkedin.client.rpc.LinkedinRemoteService;
import com.oauth.linkedin.server.service.LinkedinService;
import com.oauth.logging.OAuthLogger;

public class LinkedinGwtController extends GWTSpringController implements LinkedinRemoteService {

	private OAuthLogger logger = OAuthLogger.getLogger(this.getClass());
	private static final long serialVersionUID = -5758464341967618224L;

	@Autowired
	private LinkedinService mLinkedinService;

	/**
	 * @param pLinkedinService
	 *            the linkedinService to set
	 */
	public void setLinkedinService(LinkedinService pLinkedinService) {
		mLinkedinService = pLinkedinService;
	}

	public List<LinkedinUser> getConnections() throws LinkedinOAuthException {
		try {
			Long memberId = OAuthRequestUtil.getMemberId(getThreadLocalRequest());
			List<LinkedinUser> connections = mLinkedinService.getConnections(memberId);
			return connections;
		} catch (Exception e) {
			logger.error("Error in fetching scraps", e);
			throw new LinkedinOAuthException();
		}
	}

	public LinkedinModel getLinkedInData() throws LinkedinOAuthException {
		LinkedinModel model = new LinkedinModel();

		logger.info("Entering linkedin home controller");

		Long memberId = OAuthRequestUtil.getMemberId(getThreadLocalRequest());
		try {
			LinkedinUser user = getLoggedInUserInfo(memberId);
			model.setUser(user);
			return model;
		} catch (Exception e) {
			logger.error("Error in fetching linkedin home data", e);
			throw new LinkedinOAuthException();
		}
	}

	public LinkedinUser getLoggedInUserInfo(Long memberId) throws Exception {
		LinkedinUser profile = mLinkedinService.getLinkedinUser(memberId);
		return profile;
	}

	@Override
	public List<LinkedinUser> getUpdates() throws SessionExpiredException, LinkedinOAuthException {
		Long memberId = OAuthRequestUtil.getMemberId(getThreadLocalRequest());
		try {
			return mLinkedinService.getUpdates(memberId);
		} catch (Exception e) {
			logger.error("Error in getting linkedin updates", e);
			e.printStackTrace();
			throw new LinkedinOAuthException();
		}
	}

	@Override
	public boolean updateStatus(String pText) throws SessionExpiredException,
			LinkedinOAuthException {
		try {
			Long memberId = OAuthRequestUtil.getMemberId(getThreadLocalRequest());
			mLinkedinService.updateStatus(pText, memberId);
			return true;
		} catch (Exception e) {
			logger.error("Error in fetching scraps", e);
			throw new LinkedinOAuthException();
		}

	}

}
